using System.Collections.Generic;
using System.Collections; 
using LuaInterface;
using System;
using UnityEngine;

public class Ctrl
{
    #region
    private Dictionary<string, Proc> m_ProcDict;

    private Proc _curProc = null;

    #endregion

    #region Construct
    public Ctrl()
    {
        m_ProcDict = new Dictionary<string, Proc>();

        insertProc(new ProcUpdateClient());
        insertProc(new ProcUpdate());
        insertProc(new ProcInit());
    }
    #endregion

    #region Logic
    public void Update()
    {
        

        if (_curProc != null)
            _curProc.process();
    }

    public void FixedUpdate()
    {
        if (_curProc != null)
            _curProc.fixedUpdate();
    }

    public void insertProc(Proc f_proc)
    {
        m_ProcDict.Add(f_proc.type, f_proc);
    }

    public Proc findProc(string type)
    {
        Proc v = null;
        LuaTable luaProc = null;
        try
        {
            luaProc = AppFacade.luaManager.lua.Invoke<LuaTable>(type + ".new", false);
        }
        catch
        {  }
        

        if (luaProc != null)
        {
            v = new LuaProc(luaProc);
        }
        else
        {
            m_ProcDict.TryGetValue(type, out v);
        }
        return v;
    }

    public void changeProc(string type, string[] loadSceneNames,object[] additionalParams)
    {
        if(_curProc != null)
        {
            _curProc.onEnd();
        }
        _curProc = null;

        Proc nextProc = findProc(type);
        if(nextProc == null)
        {
            UnityEngine.Debug.LogError("Wrong Type: " + type);
        }
        else
        {
            AppFacade.gameManager.StartCoroutine(DoLoadScene(loadSceneNames, nextProc, additionalParams));
            
        }
    }

    IEnumerator DoLoadScene(string[] loadSceneNames, Proc nextProc, object[] additionalParams)
    {
        if (loadSceneNames != null)
        {
            List<UnityEngine.AsyncOperation> loadRequests = new List<UnityEngine.AsyncOperation>();
            for (int i = 0; i < loadSceneNames.Length; i++)
            {
                AppFacade.resourceManager.LoadScene(loadSceneNames[i], i != 0);
            }
        }
        yield return null;
        _curProc = nextProc;
        _curProc.onBegin(additionalParams);
    }

    public Proc CurrProc
    {
        get
        {
            return _curProc;
        }
    }
#endregion
}